package controller

import (
	"fmt"
	"github.com/RaymondCode/simple-demo/Dao"
	"github.com/RaymondCode/simple-demo/config"
	"github.com/RaymondCode/simple-demo/model"
	"github.com/gin-gonic/gin"
	"net/http"
	"strconv"
	"time"
)

type FeedResponse struct {
	model.Response
	VideoList []model.Video `json:"video_list,omitempty"`
	NextTime  int64         `json:"next_time,omitempty"`
}

// Feed same demo video list for every request
func Feed(c *gin.Context) {
	latestTimeStr := c.Query("latest_time")
	var latestTime time.Time
	var err error

	if latestTimeStr != "" {
		timestamp, err := strconv.ParseInt(latestTimeStr, 10, 64)
		if err != nil {
			c.JSON(http.StatusBadRequest, model.Response{StatusCode: 1, StatusMsg: "Invalid latest_time"})
			return
		}
		latestTime = time.Unix(timestamp, 0)
	} else {
		latestTime = time.Now()
	}

	var videos []model.Video
	err = Dao.DB.Where("create_at <= ?", latestTime).Order("create_at desc").Limit(5).Find(&videos).Error
	if err != nil {
		c.JSON(http.StatusInternalServerError, model.Response{StatusCode: 1, StatusMsg: "Database error"})
		return
	}

	// 拼接视频的 URL
	for i := range videos {
		videos[i].PlayUrl = GetFullStaticURL(videos[i].PlayUrl)
		videos[i].CoverUrl = GetFullStaticURL(videos[i].CoverUrl)
	}

	var nextTime int64
	if len(videos) > 0 {
		nextTime = videos[len(videos)-1].CreateAt.Unix()
	} else {
		nextTime = time.Now().Unix()
	}
	c.JSON(http.StatusOK, FeedResponse{
		Response:  model.Response{StatusCode: 0, StatusMsg: "Feed success"},
		VideoList: videos,
		NextTime:  nextTime,
	})
}

func GetFullStaticURL(relativePath string) string {
	return fmt.Sprintf("%s://%s%s", "http", config.StaticIP4, relativePath)
}
